package com.yulebaby.callsenter.ui.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.github.mikephil.charting.charts.BarChart;
import com.yulebaby.callsenter.R;
import com.yulebaby.callsenter.adapter.DynamicDailyAdapter;
import com.yulebaby.callsenter.bean.ResultBean;
import com.yulebaby.callsenter.bean.SaleDailyBean;
import com.yulebaby.callsenter.event.EventFactory;
import com.yulebaby.callsenter.event.QueryDailyEvent;
import com.yulebaby.callsenter.event.ShowResultEvent;
import com.yulebaby.callsenter.global.Constant;
import com.yulebaby.callsenter.http.callback.HttpCallback;
import com.yulebaby.callsenter.task.RequestTranProgressTask;
import com.yulebaby.callsenter.task.UploadTransDailyTask;
import com.yulebaby.callsenter.ui.activity.ActualTransNotesActivity;
import com.yulebaby.callsenter.ui.base.BaseFragment;
import com.yulebaby.callsenter.ui.view.StatisticalParallelColumn;
import com.yulebaby.callsenter.ui.view.YuLeBaByLinearLayoutManager;
import com.yulebaby.callsenter.utils.DateUtil;
import com.yulebaby.callsenter.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Author: Zhangbo
 * Time: 2017/1/23
 */
public class DynamicDailyFragment extends BaseFragment {


    @BindView(R.id.rv_dynaamic)
    RecyclerView mRvDynaamic;

    private StatisticalParallelColumn mColumn;
    private BarChart mBcTran;
    private List<SaleDailyBean> dataList, tranList;
    private DynamicDailyAdapter mDailyAdapter;
    private TextView mTvTime;

    public static DynamicDailyFragment newInstance() {
        Bundle args = new Bundle();
        DynamicDailyFragment fragment = new DynamicDailyFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dynamicdaily, null);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        View view = LayoutInflater.from(mActivity).inflate(R.layout.include_dynamic_header, null);
        View foot = LayoutInflater.from(mActivity).inflate(R.layout.layout_daily_foot, null);
        mBcTran = (BarChart) view.findViewById(R.id.bc_tran);
        mTvTime = (TextView) view.findViewById(R.id.tv_time);
        dataList = new ArrayList<>();
        tranList = new ArrayList<>();
        mColumn = new StatisticalParallelColumn(mBcTran);
        mDailyAdapter = new DynamicDailyAdapter(tranList);
        mDailyAdapter.addHeaderView(view);
        mDailyAdapter.addFooterView(foot);
        mRvDynaamic.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {

                SaleDailyBean bean = (SaleDailyBean) baseQuickAdapter.getItem(i);
                switch (view.getId()) {
                    case R.id.btn_addcause:
                        for (SaleDailyBean saleDailyBean : tranList) {
                            if (saleDailyBean.getItem_state() == 4) {
                                ToastUtil.showToast("您当前有正在编辑中的未完成原因，请先保存后再编辑其它步骤的未完成原因");
                                return;
                            }
                        }
                        bean.setItem_state(4);
                        baseQuickAdapter.notifyItemChanged(baseQuickAdapter.getHeaderLayoutCount() + i);
                        break;
                    case R.id.tv_actualtran: //跳跟踪进展界面
                        Intent intent = new Intent(mActivity, ActualTransNotesActivity.class);
                        intent.putExtra(Constant.TRA_PRO, bean.getStep());
                        startActivity(intent);
                        break;
                    case R.id.btn_addcause1:
                        for (SaleDailyBean saleDailyBean : tranList) {
                            if (saleDailyBean.getItem_state() == 4) {
                                ToastUtil.showToast("您当前有正在编辑中的未完成原因，请先保存后再编辑其它步骤的未完成原因");
                                return;
                            }
                        }
                        bean.setItem_state(4);
                        baseQuickAdapter.notifyItemChanged(baseQuickAdapter.getHeaderLayoutCount() + i);
                        break;
                    case R.id.btn_save_cause:
                        UploadTransDailyTask.doUploadUnfinishedCause(mActivity, bean.getStep(), bean.getUnfinished_reason(), new HttpCallback<ResultBean>() {
                            @Override
                            public void onSuccessResultNull() {
                                requestData(null);
                            }
                        });
                        break;
                    case R.id.btn_cancel:
                        if (TextUtils.isEmpty(bean.getUnfinished_reason())) {
                            bean.setItem_state(2);
                        } else {
                            bean.setItem_state(3);
                        }
                        baseQuickAdapter.notifyItemChanged(baseQuickAdapter.getHeaderLayoutCount() + i);
                        break;
                }
            }
        });

        mRvDynaamic.setLayoutManager(new YuLeBaByLinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false));
        mRvDynaamic.setAdapter(mDailyAdapter);
        requestData(null);
    }

    /**
     * 请求数据
     *
     * @param time 请求的时间
     */
    private void requestData(String time) {
        RequestTranProgressTask.doRequestDynamicDaily(mActivity, time, new HttpCallback<List<SaleDailyBean>>() {
            @Override
            public void onSuccess(List<SaleDailyBean> result) {
                super.onSuccess(result);
                processResult(result);
                EventBus.getDefault().post(EventFactory.CreateShowResultEvent(ShowResultEvent.SuccessEvent));
            }

            @Override
            public void onFailParam(String info) {
                super.onFailParam(info);
                EventBus.getDefault().post(EventFactory.CreateShowResultEvent(ShowResultEvent.FailEvent));
            }
        });
    }

    /**
     * 请求静态日报  TODO
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void staticDailyReport(QueryDailyEvent event) {
        if (event != null) {
            requestData(event.getTime()); //带时间请求
        }
    }

    /**
     * 对数据进行处理
     *
     * @param result
     */
    private void processResult(List<SaleDailyBean> result) {
        if (result != null && result.size() > 0) {
            dataList.clear();
            tranList.clear();
            dataList.addAll(result);
            tranList.addAll(result);
            tranList.remove(0);
            mTvTime.setText("今天" + DateUtil.formatDateTime(result.get(0).getCreate_time()));
            //对显示的状态进行设置
            for (SaleDailyBean bean : tranList) {
                if (bean.getCompletion_status() == 0 && !TextUtils.isEmpty(bean.getDailytype())) {
                    if (TextUtils.isEmpty(bean.getUnfinished_reason())) {
                        bean.setItem_state(2);
                    } else {
                        bean.setItem_state(3);
                    }
                } else {
                    bean.setItem_state(1);
                }
            }
            mColumn.setData(dataList);
            mDailyAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
